import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import axois from 'axios'
import {
  Toast
} from 'vant'

let store = new Vuex.Store({
  state: {
    goodsList: window.sessionStorage.getItem("goodslist") ?
      JSON.parse(window.sessionStorage.getItem("goodslist")) : [],
    checkedAll: true,
    status: '',
    goodsIndex: '',
  },
  mutations: {
    // 全选按钮的状态
    selectAllFn(state) {
      state.goodsList.filter(item => item.checked = !state.checkedAll)
    },
    checkedGoodsFn(state) {

      // 判断有没有没有复选框没有被选中
      const isExist = state.goodsList.some(item => item.checked == false)

      // 有则全选框为false
      if (isExist) {
        state.checkedAll = false
      } else {
        state.checkedAll = true
      }
    },
    addGoodsList(state, data) {
      // 如果购物车为空判断之间添加商品
      if (state.goodsList.length === 0) {
        data.checked = true
        data.goodsnum = 1
        state.goodsList.push(data)
        window.sessionStorage.setItem("goodslist", JSON.stringify(state.goodsList))

        return
      }
      // 判断商品是否已经存在购物车
      const isCunZai = state.goodsList.some(item => {

        // 存在则增加数量
        if (item.goods_id == data.goods_id) {
          console.log(item.goods_id, data.goods_id);
          item.goodsnum++
          window.sessionStorage.setItem("goodslist", JSON.stringify(state.goodsList))
        }
        return item.goods_id == data.goods_id
      })
      if (isCunZai) return
      console.log(123);
      // 不存在则添加商品
      data.checked = true
      data.goodsnum = 1
      state.goodsList.push(data)
      window.sessionStorage.setItem("goodslist", JSON.stringify(state.goodsList))
      return
    },
    // 删除购物车商品
    deteleGoods(state, id) {
      const i = state.goodsList.findIndex(item => item.goods_id == id);
      console.log(i);
      if (i != -1) { state.goodsList.splice(i, 1) }
      window.sessionStorage.setItem("goodslist", JSON.stringify(state.goodsList))
    },
    changeStatus(state, step) {
      state.status = step;
    }
  },
  actions: {
    async addGoodsFn(state, id) {
      const {
        data: res
      } = await axois.get('/goods/detail', {
        params: {
          goods_id: id
        }
      });
      if (res.meta.status != 200) return Toast.fail('添加商品失败');
      console.log(res);

      state.commit("addGoodsList", res.message)
    }
  },
  getters: {
    total(state) {
      let total = 0;
      state.goodsList.filter(item => {
        if (item.checked) {
          total += item.goods_price * item.goodsnum
        }

      })
      return Number(total + '00')
    },
    totalNum(state) {
      let totalNum = 0;
      if (state.goodsList.length === 0) return totalNum = 0
      state.goodsList.filter(item => {
        if (item.checked) {
          totalNum += item.goodsnum
        }

      })
      return totalNum
    },
    toBuyGoodsList(state) {
      return state.goodsList.filter(item => item.checked == true & item.goodsnum != 0)
    }
  }
})

export default store